<template>
  <div class="dashboard">
    <el-row :gutter="20">
      <!-- 欢迎信息 -->
      <el-col :span="24">
        <el-card class="welcome-card" shadow="hover">
          <div class="welcome-content">
            <div class="welcome-text">
              <h2>欢迎回来，{{ userStore.user?.username }}！</h2>
              <p>您的AI学习智能体门户正在等待您的探索</p>
            </div>
            <div class="welcome-actions">
              <el-button type="primary" @click="$router.push('/agents/create')">
                <el-icon><Plus /></el-icon>
                创建新智能体
              </el-button>
              <el-button @click="$router.push('/chat')">
                <el-icon><ChatRound /></el-icon>
                开始对话
              </el-button>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" class="mt-20">
      <!-- 统计卡片 -->
      <el-col :xs="24" :sm="12" :md="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon agents">
              <el-icon><Avatar /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-number">{{ stats.agentCount }}</div>
              <div class="stat-label">我的智能体</div>
            </div>
          </div>
        </el-card>
      </el-col>

      <el-col :xs="24" :sm="12" :md="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon conversations">
              <el-icon><ChatRound /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-number">{{ stats.conversationCount }}</div>
              <div class="stat-label">对话次数</div>
            </div>
          </div>
        </el-card>
      </el-col>

      <el-col :xs="24" :sm="12" :md="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon knowledge">
              <el-icon><Document /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-number">{{ stats.knowledgeCount }}</div>
              <div class="stat-label">知识库</div>
            </div>
          </div>
        </el-card>
      </el-col>

      <el-col :xs="24" :sm="12" :md="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon learning">
              <el-icon><TrendCharts /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-number">{{ stats.learningHours }}</div>
              <div class="stat-label">学习时长(小时)</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" class="mt-20">
      <!-- 我的智能体 -->
      <el-col :xs="24" :lg="12">
        <el-card class="section-card">
          <template #header>
            <div class="card-header">
              <span>我的智能体</span>
              <el-button type="text" @click="$router.push('/agents')">
                查看全部
              </el-button>
            </div>
          </template>
          
          <div v-loading="loadingAgents">
            <div v-if="recentAgents.length === 0" class="empty-state">
              <el-icon class="empty-icon"><Avatar /></el-icon>
              <p>还没有创建智能体</p>
              <el-button type="primary" @click="$router.push('/agents/create')">
                创建第一个智能体
              </el-button>
            </div>
            
            <div v-else class="agent-list">
              <div
                v-for="agent in recentAgents"
                :key="agent.id"
                class="agent-item"
                @click="$router.push(`/agents/${agent.id}`)"
              >
                <div class="agent-avatar">
                  <el-icon><Avatar /></el-icon>
                </div>
                <div class="agent-info">
                  <div class="agent-name">{{ agent.name }}</div>
                  <div class="agent-desc">{{ agent.description || '暂无描述' }}</div>
                  <div class="agent-meta">
                    <el-tag size="small" :type="getStatusType(agent.status)">
                      {{ getStatusText(agent.status) }}
                    </el-tag>
                    <span class="agent-time">{{ formatTime(agent.updated_at) }}</span>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>

      <!-- 最近对话 -->
      <el-col :xs="24" :lg="12">
        <el-card class="section-card">
          <template #header>
            <div class="card-header">
              <span>最近对话</span>
              <el-button type="text" @click="$router.push('/chat')">
                查看全部
              </el-button>
            </div>
          </template>
          
          <div v-loading="loadingConversations">
            <div v-if="recentConversations.length === 0" class="empty-state">
              <el-icon class="empty-icon"><ChatRound /></el-icon>
              <p>还没有对话记录</p>
              <el-button type="primary" @click="$router.push('/chat')">
                开始对话
              </el-button>
            </div>
            
            <div v-else class="conversation-list">
              <div
                v-for="conversation in recentConversations"
                :key="conversation.id"
                class="conversation-item"
                @click="$router.push(`/chat/${conversation.id}`)"
              >
                <div class="conversation-info">
                  <div class="conversation-title">{{ conversation.title }}</div>
                  <div class="conversation-preview">{{ conversation.last_message }}</div>
                  <div class="conversation-time">{{ formatTime(conversation.updated_at) }}</div>
                </div>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" class="mt-20">
      <!-- 学习进度 -->
      <el-col :span="24">
        <el-card class="section-card">
          <template #header>
            <div class="card-header">
              <span>学习进度</span>
              <el-button type="text" @click="$router.push('/learning')">
                查看详情
              </el-button>
            </div>
          </template>
          
          <el-row :gutter="20">
            <el-col :xs="24" :md="8">
              <div class="progress-item">
                <div class="progress-label">本周学习时长</div>
                <el-progress
                  :percentage="weeklyProgress"
                  :stroke-width="8"
                  :text-inside="true"
                  status="success"
                />
                <div class="progress-text">{{ stats.weeklyHours }}/{{ stats.weeklyTarget }} 小时</div>
              </div>
            </el-col>
            
            <el-col :xs="24" :md="8">
              <div class="progress-item">
                <div class="progress-label">智能体训练</div>
                <el-progress
                  :percentage="trainingProgress"
                  :stroke-width="8"
                  :text-inside="true"
                  status="warning"
                />
                <div class="progress-text">{{ stats.trainedAgents }}/{{ stats.totalAgents }} 个已训练</div>
              </div>
            </el-col>
            
            <el-col :xs="24" :md="8">
              <div class="progress-item">
                <div class="progress-label">知识库建设</div>
                <el-progress
                  :percentage="knowledgeProgress"
                  :stroke-width="8"
                  :text-inside="true"
                />
                <div class="progress-text">{{ stats.documentsUploaded }} 个文档</div>
              </div>
            </el-col>
          </el-row>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useUserStore } from '@/stores/user'
import { agentApi } from '@/api/agents'
import { chatApi } from '@/api/chat'
import { ElMessage } from 'element-plus'
import {
  Plus,
  ChatRound,
  Avatar,
  Document,
  TrendCharts
} from '@element-plus/icons-vue'

const userStore = useUserStore()

// 响应式数据
const loadingAgents = ref(false)
const loadingConversations = ref(false)
const recentAgents = ref([])
const recentConversations = ref([])

// 统计数据
const stats = ref({
  agentCount: 0,
  conversationCount: 0,
  knowledgeCount: 0,
  learningHours: 0,
  weeklyHours: 0,
  weeklyTarget: 40,
  trainedAgents: 0,
  totalAgents: 0,
  documentsUploaded: 0
})

// 计算属性
const weeklyProgress = computed(() => {
  return Math.min((stats.value.weeklyHours / stats.value.weeklyTarget) * 100, 100)
})

const trainingProgress = computed(() => {
  if (stats.value.totalAgents === 0) return 0
  return (stats.value.trainedAgents / stats.value.totalAgents) * 100
})

const knowledgeProgress = computed(() => {
  return Math.min(stats.value.documentsUploaded * 2, 100)
})

// 方法
const loadDashboardData = async () => {
  try {
    await Promise.all([
      loadRecentAgents(),
      loadRecentConversations(),
      loadStats()
    ])
  } catch (error) {
    console.error('加载仪表板数据失败:', error)
    ElMessage.error('加载数据失败')
  }
}

const loadRecentAgents = async () => {
  loadingAgents.value = true
  try {
    const response = await agentApi.getAgents({ limit: 5 })
    recentAgents.value = response.data.results || []
    stats.value.agentCount = response.data.count || 0
  } catch (error) {
    console.error('加载智能体失败:', error)
  } finally {
    loadingAgents.value = false
  }
}

const loadRecentConversations = async () => {
  loadingConversations.value = true
  try {
    const response = await chatApi.getConversations({ limit: 5 })
    recentConversations.value = response.data.results || []
    stats.value.conversationCount = response.data.count || 0
  } catch (error) {
    console.error('加载对话失败:', error)
  } finally {
    loadingConversations.value = false
  }
}

const loadStats = async () => {
  try {
    // 模拟统计数据
    stats.value = {
      ...stats.value,
      knowledgeCount: 5,
      learningHours: 128,
      weeklyHours: 25,
      weeklyTarget: 40,
      trainedAgents: 3,
      totalAgents: stats.value.agentCount,
      documentsUploaded: 15
    }
  } catch (error) {
    console.error('加载统计数据失败:', error)
  }
}

const getStatusType = (status) => {
  const statusMap = {
    'active': 'success',
    'training': 'warning',
    'inactive': 'info',
    'error': 'danger'
  }
  return statusMap[status] || 'info'
}

const getStatusText = (status) => {
  const statusMap = {
    'active': '活跃',
    'training': '训练中',
    'inactive': '未激活',
    'error': '错误'
  }
  return statusMap[status] || '未知'
}

const formatTime = (timeString) => {
  if (!timeString) return '未知时间'
  const date = new Date(timeString)
  const now = new Date()
  const diff = now - date
  
  const minutes = Math.floor(diff / 60000)
  const hours = Math.floor(diff / 3600000)
  const days = Math.floor(diff / 86400000)
  
  if (minutes < 60) return `${minutes}分钟前`
  if (hours < 24) return `${hours}小时前`
  return `${days}天前`
}

// 生命周期
onMounted(() => {
  loadDashboardData()
})
</script>

<style scoped lang="scss">
.dashboard {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 60px);
}

.mt-20 {
  margin-top: 20px;
}

.welcome-card {
  margin-bottom: 20px;
  
  .welcome-content {
    display: flex;
    justify-content: space-between;
    align-items: center;
    flex-wrap: wrap;
    gap: 20px;
    
    .welcome-text {
      h2 {
        margin: 0 0 8px 0;
        color: var(--el-text-color-primary);
        font-weight: 600;
      }
      
      p {
        margin: 0;
        color: var(--el-text-color-regular);
      }
    }
    
    .welcome-actions {
      display: flex;
      gap: 12px;
      flex-wrap: wrap;
    }
  }
}

.stat-card {
  margin-bottom: 20px;
  transition: transform 0.2s;
  
  &:hover {
    transform: translateY(-2px);
  }
  
  .stat-content {
    display: flex;
    align-items: center;
    
    .stat-icon {
      width: 48px;
      height: 48px;
      border-radius: 8px;
      display: flex;
      align-items: center;
      justify-content: center;
      margin-right: 16px;
      
      .el-icon {
        font-size: 24px;
        color: white;
      }
      
      &.agents {
        background: linear-gradient(135deg, #667eea, #764ba2);
      }
      
      &.conversations {
        background: linear-gradient(135deg, #f093fb, #f5576c);
      }
      
      &.knowledge {
        background: linear-gradient(135deg, #4facfe, #00f2fe);
      }
      
      &.learning {
        background: linear-gradient(135deg, #43e97b, #38f9d7);
      }
    }
    
    .stat-info {
      flex: 1;
      
      .stat-number {
        font-size: 24px;
        font-weight: 600;
        color: var(--el-text-color-primary);
        line-height: 1;
      }
      
      .stat-label {
        font-size: 14px;
        color: var(--el-text-color-regular);
        margin-top: 4px;
      }
    }
  }
}

.section-card {
  height: 100%;
  
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-weight: 600;
  }
}

.empty-state {
  text-align: center;
  padding: 40px 20px;
  color: var(--el-text-color-regular);
  
  .empty-icon {
    font-size: 48px;
    color: var(--el-text-color-placeholder);
    margin-bottom: 16px;
  }
  
  p {
    margin: 0 0 20px 0;
  }
}

.agent-list {
  .agent-item {
    display: flex;
    align-items: center;
    padding: 12px 0;
    border-bottom: 1px solid var(--el-border-color-lighter);
    cursor: pointer;
    transition: background-color 0.2s;
    
    &:hover {
      background-color: var(--el-fill-color-light);
      border-radius: 8px;
      padding-left: 12px;
      padding-right: 12px;
    }
    
    &:last-child {
      border-bottom: none;
    }
    
    .agent-avatar {
      width: 40px;
      height: 40px;
      border-radius: 50%;
      background: var(--el-color-primary);
      display: flex;
      align-items: center;
      justify-content: center;
      margin-right: 12px;
      
      .el-icon {
        font-size: 20px;
        color: white;
      }
    }
    
    .agent-info {
      flex: 1;
      
      .agent-name {
        font-weight: 500;
        color: var(--el-text-color-primary);
        margin-bottom: 4px;
      }
      
      .agent-desc {
        font-size: 13px;
        color: var(--el-text-color-regular);
        margin-bottom: 6px;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
      
      .agent-meta {
        display: flex;
        align-items: center;
        gap: 8px;
        
        .agent-time {
          font-size: 12px;
          color: var(--el-text-color-placeholder);
        }
      }
    }
  }
}

.conversation-list {
  .conversation-item {
    padding: 12px 0;
    border-bottom: 1px solid var(--el-border-color-lighter);
    cursor: pointer;
    transition: background-color 0.2s;
    
    &:hover {
      background-color: var(--el-fill-color-light);
      border-radius: 8px;
      padding-left: 12px;
      padding-right: 12px;
    }
    
    &:last-child {
      border-bottom: none;
    }
    
    .conversation-info {
      .conversation-title {
        font-weight: 500;
        color: var(--el-text-color-primary);
        margin-bottom: 6px;
      }
      
      .conversation-preview {
        font-size: 13px;
        color: var(--el-text-color-regular);
        margin-bottom: 6px;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
      
      .conversation-time {
        font-size: 12px;
        color: var(--el-text-color-placeholder);
      }
    }
  }
}

.progress-item {
  text-align: center;
  
  .progress-label {
    font-size: 14px;
    color: var(--el-text-color-regular);
    margin-bottom: 12px;
  }
  
  .progress-text {
    font-size: 12px;
    color: var(--el-text-color-placeholder);
    margin-top: 8px;
  }
}

@media (max-width: 768px) {
  .dashboard {
    padding: 12px;
  }
  
  .welcome-content {
    flex-direction: column;
    align-items: flex-start !important;
    
    .welcome-actions {
      width: 100%;
      justify-content: center;
    }
  }
}
</style>